package com.btkjgc.controller;

import com.btkjgc.models.AdminUser;
import com.btkjgc.models.Role;
import com.btkjgc.service.impl.AdminUserManageService_Impl;
import com.btkjgc.service.intf.AdminUserManageService_Intf;
import com.btkjgc.utils.DataDisplayUtil;
import com.btkjgc.utils.HibernateUtil;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import java.util.Enumeration;
import java.util.List;
import java.util.Map;

@Controller
public class AdminUserManageController
{
	static Logger logger = Logger.getLogger(AdminUserManageController.class);

	private AdminUserManageService_Intf adminuserManageService;

	@RequestMapping(value = "admin_user_manage", method = { RequestMethod.GET,
			RequestMethod.POST })
	public ModelAndView getBusinessRecords(HttpServletRequest request)
	{
		doPostAction(request);
		ModelAndView mv = new ModelAndView("admin_user_manage");
		listrecord(request, mv);
		addFunction(request, mv);
		return mv;
	}

	@SuppressWarnings("unchecked")
	public void addFunction(HttpServletRequest request, ModelAndView mv)
	{
		Map<String, Map<String, Boolean>> functionMap = (Map<String, Map<String, Boolean>>) request
				.getSession().getAttribute("role_function");
		if (functionMap != null)
		{
			Map<String, Boolean> map = functionMap.get(request.getRequestURI());
			if (map != null)
			{
				if (map.get("role") != null)
				{
					mv.addObject("role", true);
				}
			}
		}
	}

	@SuppressWarnings("unchecked")
	private void listrecord(HttpServletRequest request, ModelAndView mv)
	{
		AdminUser adminUser = (AdminUser) request.getSession().getAttribute(
				"user");
		mv.addObject("user_info", adminUser);

		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements())
		{
			String name = names.nextElement();
			mv.addObject(name, request.getParameter(name));
		}

		String hqlForEntityName = "select name from Entity where id=?";
		List<String> entityNameList = HibernateUtil
				.executeQuery(hqlForEntityName,
						new String[] { adminUser.getEntityid() + "" });
		if (entityNameList.size() > 0)
		{
			adminUser.setEntityname(entityNameList.get(0));
		}
		else
		{
			adminUser.setEntityname("");
		}
		adminuserManageService = new AdminUserManageService_Impl();

		String username = request.getParameter("username");
		String entityname = request.getParameter("entityname");
		String sortfield = request.getParameter("sortfield");
		String page = request.getParameter("page");

		String addUserName = request.getParameter("addUserName");
		if (addUserName == null)
		{
			mv.addObject("addUserName", "");
		}
		else
		{
			mv.addObject("addUserName", addUserName);
		}
		mv.addObject("addPassword", "");
		mv.addObject("addPassword2", "");
		mv.addObject("addUserSex", "");
		mv.addObject("addEntityName", "");
		mv.addObject("addRole", "");
		mv.addObject("addPhone", "");
		mv.addObject("addEmail", "");
		mv.addObject("dataDisplayUtil", new DataDisplayUtil());
		int pageIndex = 0;
		if (page != null)
		{
			pageIndex = Integer.parseInt(page);
		}

		int totalRecord = adminuserManageService.getCount(adminUser, username,
				entityname);
 
		AdminUser usr = (AdminUser) request.getSession().getAttribute("user");
		String pid = usr.getEntityid() + "";
		String hql2 = "from Entity where parentid=? or id =?";
		String[] parameter2 = { pid, pid };
 

		String hqllevel = "FROM Role where id in (select roleid from AdminUserRole where userid = ?)";
		List<Role> adminLevelList = HibernateUtil.executeQuery(hqllevel,
				new String[] { adminUser.getId() + "" });
		if (adminLevelList.size() > 0)
		{
			Role adminLevel = adminLevelList.get(0);
			String hqlrole = "from Role where id>? AND level<=?";
			List<Role> rolelist = HibernateUtil.executeQuery(hqlrole,
					new String[] { "0", adminLevel.getLevel() + "" });
			mv.addObject("rolelist", rolelist);
		}
		else
		{
		}
		if (entityname == null)
		{
			mv.addObject("entityname", "");
		}
		if (sortfield == null)
		{
			mv.addObject("sortfield", "");
		}
		if (username == null)
		{
			mv.addObject("username", "");
		}

		mv.addObject("currentpage", pageIndex);
		mv.addObject("totalRecord", totalRecord);
	}

	public int doPostAction(HttpServletRequest request)
	{
		String postaction = request.getParameter("postactionorder");
		if (postaction != null && postaction.length() > 0)
		{
			if ("deleteUser".equals(postaction))
			{
				String postarg = request.getParameter("postarg");
				int adminUserId = Integer.valueOf(postarg);
				adminuserManageService.deleteById(adminUserId);
				return 1;
			}
			if ("resetPW".equals(postaction))
			{
				String postarg = request.getParameter("postarg");
				int adminUserId = Integer.valueOf(postarg);
				adminuserManageService.resetPWById(adminUserId);
				return 1;
			}
			if ("changePW".equals(postaction))
			{
				String postarg = request.getParameter("postarg");
				String PW = request.getParameter("myText");
				int adminUserId = Integer.valueOf(postarg);
				adminuserManageService.changePWById(adminUserId, PW);
				return 2;
			}
			if ("update".equals(postaction))
			{
				String postarg = request.getParameter("postarg");
				int adminUserId = Integer.valueOf(postarg);
				String role = request.getParameter("editRole");
				adminuserManageService.updateAdminUserRole(adminUserId, role);
				return 1;
			}
		}
		return 0;
	}

	@RequestMapping(value = "add_adminuser_in_admin_user_manage_ftl/{a}", method = RequestMethod.GET)
	public @ResponseBody
	Integer jsonAddAdminUser(HttpServletRequest request,
			@PathVariable("a") int a)
	{
		String addUserName = request.getParameter("addUserName");
		String addPassword = request.getParameter("addPassword");
		String addEntityName = request.getParameter("addEntityName");
		String addEntityId = request.getParameter("addEntityId");
		String addRole = request.getParameter("addRole");
		String addUserSex = request.getParameter("addUserSex");
		String addPhone = request.getParameter("addPhone");
		String addEmail = request.getParameter("addEmail");
		AdminUserManageService_Impl userManageService = new AdminUserManageService_Impl();
		if ((addEntityName != null && addEntityName.length() > 0)
				|| (addEntityId != null && addEntityId.length() > 0))
		{

			Integer reInt = adminuserManageService.insertAdminUser(addEntityId,
					addUserName, addPassword, addEntityName, addRole,
					addUserSex, addPhone, addEmail);
			return reInt;

		}
		return -1;
	}
}
